<template>
  <div class="container">
    <data-view
      ref="dataView"
      propViewKey="sys_role"
      propViewForm="sys/role/detail.vue"
      @view-ready="handleDataviewReady"
      @extra-button-click="handleExtraButtonClick"
      :propHidePageSearch=false
      :propIsTdesign="true"
    />
  </div>
</template>

<script>

export default {
  name: 'role',
  data() {
    return {
      currentRow: {},
      userTreeData: [],
      userTreeFilter: '',
      userSelectVisible: false,
      selectedUser: [],
      menuTreeData: [],
      menuTreeFilter: '',
      menuSelectVisible: false,
      selectedMenu: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      }
    }
  },
  created() {
    this.loadTree()
  },
  components: {
  },
  watch: {
    menuTreeFilter(val) {
      this.$refs.menuTree.filter(val)
    },
    userTreeFilter(val) {
      this.$refs.userTree.filter(val)
    }
  },
  methods: {
    handleDataviewReady() {
      this.$refs.dataView.setDeletePrompt('此操作将删除该角色所有的相关信息，确定要继续吗？')
      this.$refs.dataView.setButtonInvisible('view', 'vb-add', false)
      this.$refs.dataView.setButtonInvisible('row', 'vrb-edit', false)
    },
    loadTree() {
      // 加载用户数据
      this.$ajax.get('/user/tree', {}).then(response => {
        if (response.code == 0) {
          const userTreeData = this.getTreeVisibleData(response.data)
          this.userTreeData = global.utils.convertToTree(userTreeData, {
            rootNode: {id: '0', parentId: '-1', name: '根节点' },
            keyFieldName: 'id',
            parentFieldName: 'parentId',
            labelFieldName: 'name'
          })
        } else {
          this.utilMessage.error(response.msg)
        }
      })
      // 加载菜单数据
      this.$ajax.get('/menu/all', {}).then(response => {
        if (response.code == 0) {
          const rootNode = {
            id: '0',
            title: '根节点',
            parentId: 'none'
          }
          this.menuTreeData = global.utils.convertToTree(response.data, {
            rootNode,
            keyFieldName: 'id',
            parentFieldName: 'parentId',
            labelFieldName: 'title'
          })
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    getTreeVisibleData(data) {
      const visibleData = []
      const trueLeafNodes = data.filter(val => val.type == 1)
      trueLeafNodes.forEach(node => {
        this.setParentShow(data, node.parentId)
      })
      data.forEach((node, index) => {
        if (node.isShow || node.type == 1) {
          visibleData.push(node)
        }
      })
      return visibleData
    },
    setParentShow(data, parentId) {
      const node = data.find(item => item.id == parentId)
      if (node) {
        node.isShow = true
        this.setParentShow(data, node.parentId)
      }
    },
    handleMemberSelect() {
      const selectedKeyArray = []
      const selectedNodes = this.$refs.userTree.getCheckedNodes()
      selectedNodes.forEach(node => {
        if (node.meta && node.meta.type && node.meta.type == 1) {
          selectedKeyArray.push(node.id)
        }
      })
      const params = {
        roleId: this.currentRow.id,
        userIds: selectedKeyArray.join(',')
      }
      this.$ajax.post('/roleuser/saveByUserIds', params).then(response => {
        if (response.code == 0) {
          this.userSelectVisible = false
          this.utilMessage.success('组成员保存成功！')
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    handleCloseUserSelect() {
      this.userSelectVisible = false
    },
    handleMemberClose(done) {
      done()
    },
    handleuserTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleMenuSelect() {
      const selectedKeyArray = []
      const selectedNodes = this.$refs.menuTree.getCheckedNodes(false, true)
      selectedNodes.forEach(node => {
        /*if (node.meta && node.meta.url && node.meta.url.length > 0) {
          selectedKeyArray.push(node.id)
        }*/
        selectedKeyArray.push(node.id)
      })
      const params = {
        roleId: this.currentRow.id,
        resourceIds: selectedKeyArray.join(','),
        targetType: 'R'
      }
      this.$ajax.post('/authority/role/save', params).then(response => {
        if (response.code == 0) {
          this.menuSelectVisible = false
          this.utilMessage.success('权限保存成功！')
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    handleMenuClose(done) {
      done()
    },
    handleCloseMenuSelect() {
      this.menuSelectVisible = false
    },
    handlemenuTreeFilter(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    handleExtraButtonClick(para) {
      this.currentRow = para.data
      if (para.button.key === 'authority') {
        this.showRoleAuthority()
      } else if (para.button.key === 'member') {
        this.showRoleUser()
      }
    },
    showRoleAuthority() {
      const url = `/authority/role/${this.currentRow.id}`
      this.selectedMenu = []
      this.menuSelectVisible = true
      this.$ajax.get(url, {}).then(response => {
        if (response.code == 0) {
          response.data.forEach(item => {
            this.selectedMenu.push(item.resourceId)
            this.$refs.menuTree.setChecked(item.resourceId, true, false)
          })
          // this.$refs.menuTree.setCheckedKeys(this.selectedMenu)
        } else {
          this.utilMessage.error(response.msg)
        }
      })
    },
    showRoleUser() {
      const url = `/roleuser/listByRoleId/${this.currentRow.id}`
      this.selectedUser = []
      this.userSelectVisible = true
      this.$ajax.get(url, {}).then(response => {
        response.data.forEach(item => {
          this.selectedUser.push(item.userId)
          this.$refs.userTree.setChecked(item.userId, true, false)
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .container {
    height: 100%;
    background-color: #fff;
  }
  .tree-container {
    height:50vh;
    margin:10px;
    overflow:auto;
    border:1px solid lightgray
  }
  .tree-filter {
    margin-left:10px;
    width:50%
  }
  .btn-sure {
    float:right;
    margin-right:10px;
    width:100px
  }
  .btn-cancel {
    float:right;
    margin-right:10px;
    width:50px
  }
</style>
